package cn.flightcloud.service.file.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.flightcloud.service.file.MutilFileInfo;
import cn.flightcloud.service.file.service.FileManagerService;

@Controller
public class UploadController {
	@Autowired
	private FileManagerService fileManagerService;

	@RequestMapping("index")
	public String index() {
		return "index";
	}

	/**
	 * 文件上传
	 * 
	 * @param      fileInfo:文件参数实体类
	 * @param file 附件字节码文件
	 * @return 返回处理结果，请求头200:成功,500:失败
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> MutiluploadFile(MutilFileInfo fileinfo,
			@RequestParam(required = false, value = "file") MultipartFile file, HttpServletResponse response)
			throws Exception {
		try {
			if (file != null && !file.isEmpty()) {
				if (MutilFileUploadUtils.checkMutiFilePremeter(fileinfo)) { // 切片上传
					fileManagerService.saveMutiBurstFiletoDir(fileinfo, file);
				} else if (MutilFileUploadUtils.checkSingleFilePremeter(fileinfo)) {// 单文件整体上传
					fileManagerService.saveSingleFiletoDir(fileinfo, file);
				} else {
					throw new ErrorPremetersException("文件上传参数不合法");
				}
			} else {
				throw new ErrorPremetersException("文件上传附件字节流内容为空");
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.setStatus(500);
		}
		return null;
	}

	/**
	 * 文件分片合并
	 * 
	 * @return 返回处理结果，请求头200:成功,500:失败
	 * @throws Exception
	 */
	@RequestMapping(value = "/mergingChunks", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> MutilMergingChunksForFile(MutilFileInfo fileinfo, HttpServletResponse response)
			throws Exception {
		try {
			fileManagerService.MutilMergingChunks(fileinfo);
		} catch (Exception e) {
			e.printStackTrace();
			response.setStatus(500);
		}
		return null;
	}

	/**
	 * 文件分片合并
	 * 
	 * @return 返回处理结果，请求头200:成功,500:失败
	 * @throws Exception
	 */
	@RequestMapping(value = "/")
	public String uploaderView(HttpServletRequest request) throws Exception {
		HttpSession session = request.getSession();
		System.out.println(session);
		return "redirect:/index";
	}

}
